package com.cspg.design.ui.advise;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.opengl.Visibility;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Switch;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.ActivityChooserView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.cspg.design.R;
import com.cspg.design.bean.UserInfo;
import com.cspg.design.common.Constant;
import com.cspg.design.dto.ProjectFilePath;
import com.cspg.design.presenter.ProjectPresenter;
import com.cspg.design.ui.document.CommonWebViewActivity;
import com.cspg.design.ui.document.PdfReaderActivity;
import com.cspg.design.ui.login.LoginActivity;
import com.cspg.design.utils.ActionBarUtil;
import com.cspg.design.utils.AppManager;
import com.cspg.design.utils.ShowSystemUIUtil;
import com.cspg.design.utils.StatusBarUtil;
import com.cspg.design.widget.BaseDragZoomImageView;
import com.cspg.design.widget.MatrixImageView;
import com.cspg.design.widget.ToastUtils;

import java.io.File;
import java.sql.BatchUpdateException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class AdviseActivity extends AppCompatActivity {

    private ListView mFileListView;
    private ProjectPresenter projectPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_advise);
        shouquan();
        StatusBarUtil.setStatusBarColor(this, R.color.colorPrimary);
        ActionBarUtil.setActionBar(this, R.string.examine_advise);
        AppManager.getAppManager().addActivity(this);
        mFileListView = findViewById(R.id.lv_file);
        View view = ActivityChooserView.InnerLayout.inflate(this, R.layout.list_advise_footer, null);
        mFileListView.addFooterView(view);
        Intent intent = getIntent();
        final String projectId = intent.getStringExtra("projectId");
        if (projectId == null) {
            ToastUtils.toast(this, "项目ID获取失败");
            return;
        }
        LinearLayout llIsWork = view.findViewById(R.id.ll_is_work);
        final Switch isWork = view.findViewById(R.id.st_examine_advise);
        if (UserInfo.getInstance().UserRight != 2) {
            llIsWork.setVisibility(View.GONE);
        } else {
            isWork.setChecked(false);
        }
        isWork.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isWork.isChecked()) {
                    //如果是需要添加方案进行跳转
                    Intent intent = new Intent();
                    intent = new Intent(AdviseActivity.this, LiveWorkingActivity.class);//文件通过微信接收下载名称一致即可
                    intent.putExtra("projectId", projectId);
                    startActivity(intent);
                }
            }
        });
        Button btnOK = view.findViewById(R.id.btn_examine_advise_ok);
        Button btnNO = view.findViewById(R.id.btn_examine_advise_no);
        final EditText text = view.findViewById(R.id.et_examine_advise);
        btnOK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String txt = text.getText().toString();
                projectPresenter.getProjectSubmit(projectId, UserInfo.getInstance().EmployeeID, true, txt);
            }
        });
        btnNO.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String txt = text.getText().toString();
                if (txt.isEmpty())
                {
                    ToastUtils.toast(AdviseActivity.this,"请输入意见");
                }
                else
                {
                    new AlertDialog.Builder(AdviseActivity.this).setTitle("警告").setIcon(R.drawable.ic_info)
                            .setCancelable(false).setMessage("是否确认不通过。。。。")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    projectPresenter.getProjectSubmit(projectId, UserInfo.getInstance().EmployeeID, false, txt);
                                }
                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).show();
                }
            }
        });
        final BaseDragZoomImageView ivFile = findViewById(R.id.iv_file);
        final ConstraintLayout llFile = findViewById(R.id.cl_file);
        llFile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (llFile.getVisibility() == View.VISIBLE) {
                    llFile.setVisibility(View.GONE);
                } else {
                    llFile.setVisibility(View.VISIBLE);
                }
            }
        });
        final Button btnCancel = findViewById(R.id.btn_img_cancel);
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (llFile.getVisibility() == View.VISIBLE) {
                    llFile.setVisibility(View.GONE);
                } else {
                    llFile.setVisibility(View.VISIBLE);
                }
            }
        });


        mFileListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                List<ProjectFilePath> projectFilePathList = projectPresenter.getProjectFilePath();
                if (position < projectFilePathList.size()) {
                    ProjectFilePath projectFilePath = projectFilePathList.get(position);
                    String fileName = projectFilePath.getFileName();
                    fileName = fileName.replace(" ","");
                    if (fileName.contains(".")) {
                        String[] paths = fileName.split("\\.");
                        if (paths.length > 0) {
                            String fileType = paths[paths.length - 1];
                            fileType = fileType.toLowerCase();
                            Intent intent = null;
                            if (fileType.equals("pdf")) {
                                //打开文件
                                //startActivity(new Intent(AdviseActivity.this, PdfReaderActivity.class));
                                intent = new Intent(AdviseActivity.this, CommonWebViewActivity.class);//文件通过微信接收下载名称一致即可
                                intent.putExtra("filePath",projectFilePath.getFilePath());
                                intent.putExtra("fileType",fileType);
//                                intent.putExtra("filePath","http://www.blueerdos.top/dwz/Public/upload/345.xlsx");
//                                intent.putExtra("fileType","xlsx");
                                startActivity(intent);
                            } else if (fileType.equals("jpg")
                                    || fileType.equals("png")
                                    || fileType.equals("jpeg")
                                    || fileType.equals("gif")) {
                                llFile.setVisibility(View.VISIBLE);
                                ivFile.setImageDrawable(null);
                                projectPresenter.getProjectFile(projectId,projectFilePath.getFilePath(),fileName, ivFile);
                            } else if (
                                    fileType.equals("doc")
                                    || fileType.equals("docx")
                                    || fileType.equals("xlsx")
                                    || fileType.equals("xls")
                                    || fileType.equals("pptx")
                                    || fileType.equals("ppt")) {
                                //打开Office文档
//                                File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) , "周末加班统计.xlsx");
                                intent = new Intent(AdviseActivity.this, CommonWebViewActivity.class);//文件通过微信接收下载名称一致即可
//                                intent.putExtra("url", projectFilePath.getFilePath());  //"/storage/emulated/0/tencent/111.xlsx");
//                                intent.putExtra("isOpenFile", true);
                                intent.putExtra("filePath",projectFilePath.getFilePath());
                                intent.putExtra("fileType",fileType);
                                startActivity(intent);

                            } else if (fileType.equals("txt")) {
                                //打开文本文件
                            } else if (fileType.equals("htm") || fileType.equals("html")) {
                                //打开网页
                            }
                        }
                    }
                }
            }
        });

        List<HashMap<String, String>> hashMaps = new ArrayList<>();
        SimpleAdapter simpleAdapter = new SimpleAdapter(this, hashMaps, R.layout.listview_advise_item, new String[]{"file"}, new int[]{R.id.tv_listView_advise_item_file});
        mFileListView.setAdapter(simpleAdapter);

        projectPresenter = new ProjectPresenter(this, mFileListView, simpleAdapter, hashMaps);
        projectPresenter.getProjectFilePath(projectId);
    }

    /**
     * 点击空白区域隐藏键盘.
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (AdviseActivity.this.getCurrentFocus() != null) {
                if (AdviseActivity.this.getCurrentFocus().getWindowToken() != null) {
                    imm.hideSoftInputFromWindow(AdviseActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        }
        return super.onTouchEvent(event);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void shouquan() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//如果 API level 是大于等于 23(Android 6.0) 时  
            //判断是否具有权限  
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                //判断是否需要向用户解释为什么需要申请该权限  
                if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                        Manifest.permission.ACCESS_COARSE_LOCATION)) {
                    Toast.makeText(AdviseActivity.this, "自Android 6.0开始需要打开位置权限", Toast.LENGTH_SHORT).show();
                }
                //请求权限  
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
                                Manifest.permission.INTERNET,
                                Manifest.permission.ACCESS_NETWORK_STATE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.READ_PHONE_STATE,
                                Manifest.permission.ACCESS_WIFI_STATE,
                                Manifest.permission.CHANGE_WIFI_STATE,
                                Manifest.permission.READ_EXTERNAL_STORAGE},
                        2);
            }
        }
    }
}